<?php

class InfopagesInstall
{
	private $_config = array(
		'name' => 'infopages',
		'title' => 'Infopages module',
		'dependencies' => array(
			'editor',
			'languages' => array(
				'{{infopages}}'=>array(
					'fields' => array (
						'title' => 'varchar(255) NOT NULL',
						'body' => 'text NOT NULL'
					)
				)
			),
			'seo' => array(
				'rules' => array(
					'infopages/default/view'=>array(
						'template'=>'<title>',
						'model'=>'Infopages',
						'path'=>'application.modules.infopages.models.Infopages'
					),
				)
			),
		),
		'import' => array(
			'application.modules.infopages.InfopagesModule',
		)
	);

	public function config()
	{
		return $this->_config;
	}
	
	public function install()
	{
		$languages = Languages::model()->getLanguages();	

		foreach ($languages as $language)
		{
			foreach ($this->_config['dependencies']['languages']['{{infopages}}']['fields'] as $field => $type)
			{
				$keys[] = $field.'_'.$language['code'];
				$values[] = ':'.$field.'_'.$language['code'];
				$fields[] = "`".$field."_".$language['code']."` ".$type.",";
			}
		}

		$sql = "DROP TABLE IF EXISTS {{infopages}};";
		Yii::app()->db->createCommand($sql)->execute();

		$sql="
	CREATE TABLE IF NOT EXISTS {{infopages}} (
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `active` tinyint(1) NOT NULL,
	  `sorter` tinyint(4) NOT NULL,";
		$sql .= implode("", $fields);
		$sql .= "
	  `date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	  PRIMARY KEY (`id`)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
		Yii::app()->db->createCommand($sql)->execute();

		$sql="INSERT INTO {{infopages}} (active, sorter, ".implode(', ', $keys).", date_updated) VALUES (:active, :sorter, ".implode(', ', $values).", :date_updated);";
		$command = Yii::app()->db->createCommand($sql);

		$command->bindValue(":active", 1, PDO::PARAM_INT);
		$command->bindValue(":sorter", 1, PDO::PARAM_INT);
		foreach ($languages as $language)
		{
			$command->bindValue(":title_".$language['code'], Yii::t('InfopagesModule.install', 'About us', array(), null, $language['code']), PDO::PARAM_STR);
			$command->bindValue(":body_".$language['code'], Yii::t('InfopagesModule.install', 'About company', array(), null, $language['code']), PDO::PARAM_STR);
		}
		$command->bindValue(":date_updated", "2012-04-15 20:48:56", PDO::PARAM_STR);
		$command->execute();
	}

	public function uninstall()
	{
		Yii::app()->db->createCommand()->dropTable('{{infopages}}');
	}
}